# -*- coding: utf-8 -*-
# kate: space-indent on; tab-width 4; indent-width 4; indent-mode python; backspace-indents; encoding utf-8; line-numbers on; remove-trailing-space on;
#   Copyright 2009, 2010 Thomas Olsen <tanghus@gmail.com>
#
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU Library General Public License as
#   published by the Free Software Foundation; either version 2 or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#
#   GNU General Public License for more details
#
#
#   You should have received a copy of the GNU Library General Public
#   License along with this program; if not, write to the
#   Free Software Foundation, Inc.,
#
#   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
#

#from PyQt4 import QtCore
from PyQt4.QtCore import Qt, pyqtSlot, QVariant, QString, SIGNAL
from PyQt4.QtGui  import QWidget, QGraphicsWidget, QGraphicsLinearLayout, QSizePolicy, QAction, QTableWidgetItem
from PyKDE4.kdeui import KIcon, KDialog
from PyKDE4.kdecore import i18n
from PyKDE4.plasma import Plasma
from NetworkMonitor import NetworkMonitor
#from Notifier import Notifier
from base import BaseApplet
from LastFMEvents import LastFMEvents
from Locations import Locations
from evocation_config_ui import *
from social_networks_config_ui import *
from socialnetworks import socialnetworks

class EvocationConfig(QWidget,Ui_EvocationConfig):
    def __init__(self,parent):
        QWidget.__init__(self,parent)
        self.setupUi(self)
        #self.connect(self.localTimeZone, SIGNAL("stateChanged(int)"), self, SLOT("slotLocalTimeZoneToggled(int)"))

class SocialNetworksConfig(QWidget,Ui_SocialNetworksConfig):
    def __init__(self,parent):
        QWidget.__init__(self,parent)
        self.setupUi(self)
        #self.connect(self.localTimeZone, SIGNAL("stateChanged(int)"), self, SLOT("slotLocalTimeZoneToggled(int)"))

class LastFMEventsApplet(BaseApplet):

    def __init__(self,parent,args=None):
        BaseApplet.__init__(self, parent)

    def init(self):
        BaseApplet.init(self, needsversion="4.5")
        if self.hasFailedToLaunch():
            return

        sns = socialnetworks.keys()
        sns.sort()
        sns = ",".join(sns)
        self.socialnetworks = str(self.cfg.readEntry("socialnetworks", QString(sns)).toString()).split(",")

        self._widget = None
        self.locations = None
        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.theme = Plasma.Svg(self)
        self.setBackgroundHints(Plasma.Applet.TranslucentBackground)

        self.nwmon = NetworkMonitor()
        self._widget = LastFMEvents(self)
        self._widget.init()

        self.setGraphicsWidget(self._widget)
        self.applet.setPassivePopup(True)
        self.setPopupIcon('text-x-python')
        # for some odd reason this has to be called twice..?
        self.setGraphicsWidget(self._widget)

        # Tool tip for panel
        self.metadata = self.package().metadata()
        self.tooltipdata = Plasma.ToolTipContent()
        self.tooltipdata.setMainText(self.metadata.name())
        self.tooltipdata.setSubText(self.metadata.description())
        self.tooltipdata.setImage(KIcon('text-x-python'))
        Plasma.ToolTipManager.self().setContent(self.applet, self.tooltipdata)

        # Only register the tooltip in panels
        #if (self.formFactor() != Plasma.Planar):
        if ((self.formFactor() == Plasma.Horizontal) or (self.formFactor() == Plasma.Vertical)):
            print("PyPopupApplet: In Panel")
            Plasma.ToolTipManager.self().registerWidget(self.applet)
        else:
            Plasma.ToolTipManager.self().unregisterWidget(self.applet)
            print("PyPopupApplet: Not in Panel")

        if self.nwmon.connected():
            self.locations = Locations()

    # This should be called when hovering over the plasmoid when docked in the
    # panel but as of KDE SC 4.5.3 it isn't :-/
    @pyqtSlot(name="toolTipAboutToShow")
    def toolTipAboutToShow(self):
        print "PyPopupApplet:toolTipAboutToShow"

    def createConfigurationInterface(self, dialog):
        # General settings
        self.evo_ui = EvocationConfig(dialog)
        self.evo_ui.country.currentIndexChanged.connect(self.config_country_changed)
        for country in self.locations.countries():
            self.evo_ui.country.addItem(country)
        self.evo_ui.country.setCurrentIndex(self.evo_ui.country.findText(QString(self._widget.country)))
        self.evo_ui.distance.setValue(self._widget.distance)
        self.evo_ui.update_interval.setValue(self._widget.update_interval)
        p = dialog.addPage(self.evo_ui, i18n("General") )
        p.setIcon( KIcon(self.package().filePath("images", "%s.png" % "evocation")) )

        # Select which social networks to use.
        self.sn_ui = SocialNetworksConfig(dialog)
        #self.sn_ui.country.currentIndexChanged.connect(self.config_country_changed)
        self.sn_ui.table_sn.setRowCount(len(socialnetworks.keys()))
        names = socialnetworks.keys()
        names.sort()
        i = 0
        for name in names:
            print "SN: " + socialnetworks[name]["name"]
            sn = QTableWidgetItem(KIcon(self.package().filePath("images", "%s.png" % name)),
                                socialnetworks[name]["name"]
                                )
            sn.setData(Qt.UserRole, name)
            #sn.setFlags(Qt.ItemIsSelectable|Qt.ItemIsUserCheckable)
            print "Is '%s' in '%s'?" % (name, str(self.socialnetworks))
            if name in self.socialnetworks:
                print "Yep"
                sn.setCheckState(Qt.Checked)
            else:
                print "Nope"
                sn.setCheckState(Qt.Unchecked)
            self.sn_ui.table_sn.setItem(i, 0, sn)
            i+=1
        self.sn_ui.setEnabled(True)
        p = dialog.addPage(self.sn_ui, i18n("Social Networks") )
        p.setIcon( KIcon(self.package().filePath("images", "%s.png" % "openshareicon")) )

        dialog.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel | KDialog.Apply)))
        dialog.showButton(KDialog.Apply, False)

        dialog.applyClicked.connect(self.configAccepted)
        dialog.okClicked.connect(self.configAccepted)
        #self.connect(dialog, SIGNAL("applyClicked()"), self, SLOT("configAccepted()"))
        #self.connect(dialog, SIGNAL("okClicked()"), self, SLOT("configAccepted()"))

        self.evo_ui.update_interval.setValue(self._widget.update_interval)

    @pyqtSlot(int, name="config_country_changed")
    def config_country_changed(self, country):
        #print "config_country_changed " + str(country)
        country = self.evo_ui.country.itemText(country)
        #print "config_country_changed " + country
        self.evo_ui.metro.clear()
        for metro in self.locations.metros(str(country)):
            self.evo_ui.metro.addItem(metro)
        self.evo_ui.metro.setCurrentIndex(self.evo_ui.metro.findText(QString(self._widget.metro)))

    @pyqtSlot(name="configAccepted")
    def configAccepted(self):
        print "EvocationApplet::configAccepted"
        self._widget.country = self.evo_ui.country.currentText()
        print "Country: " + self._widget.country
        self._widget.metro = self.evo_ui.metro.currentText()
        print "Metro: " + self._widget.metro
        self._widget.distance = self.evo_ui.distance.value()
        print "Distance: " + str(self._widget.distance)
        self._widget.update_interval = self.evo_ui.update_interval.value()
        print "Interval: " + str(self._widget.update_interval)
        self.cfg.writeEntry("update_interval", QVariant(self._widget.update_interval))
        self.cfg.writeEntry("distance", QVariant(self._widget.distance))
        self.cfg.writeEntry("country", self._widget.country)
        self.cfg.writeEntry("metro", self._widget.metro)

        # Social networks
        sns = self.sn_ui.table_sn.selectedItems()
        items = []
        rows = self.sn_ui.table_sn.rowCount()
        i = 0
        while i < rows:
            sn = self.sn_ui.table_sn.item(0, i)
            if sn:
                if sn.checkState() == Qt.Checked:
                    print sn.data(Qt.UserRole).toString()
                    items.append(str(sn.data(Qt.UserRole).toString()))
            else:
                print "Couldn't get item at %d. Got '%s' instead" % (i, str(sn))
            i += 1
        self.socialnetworks = items
        self.cfg.writeEntry("socialnetworks", ",".join(items))
        print items

        self.constraintsEvent(Plasma.SizeConstraint)
        self.update() # What does this do?
        self._widget.clear()
        self._widget.start_timer()
        self.emit(SIGNAL("configNeedsSaving()"))

    def contextualActions(self):
        # Add custom context menus
        print "EvocatorApplet::contextualActions"
        actions = []
        ac_update = QAction(KIcon("view-refresh"), i18n("Update now"), self)
        #checkNow = QAction(KIcon(self.package().path() + "contents/icons/check.svg"), "Check email now", self)
        self.connect(ac_update, SIGNAL("triggered()"), self._widget.update_events)
        actions.append(ac_update)
        return actions

def CreateApplet(parent):
  return LastFMEventsApplet(parent)